package com.fingard.dsp.bank.directbank.cmbc01;

import java.util.Date;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.util.secret.salary.FieldHiddenUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;


public class CMBC01Base extends DirectBase {

    protected void writeCommonHeader(XmlTextWriter xmlWriter, CMBC01Header p_bankHeader) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.trnCode)) {
            throw new Exception("未赋值trnCode");
        }
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElementByAttr("CMBC", "<CMBC header=\"100\" version=\"100\" security=\"none\" lang=\"chs\" trnCode=\"" + p_bankHeader.trnCode + "\">");
        xmlWriter.writeStartElement("requestHeader");
        xmlWriter.writeElementString("dtClient", Format.DateTimeFormat.format(new Date()));
        xmlWriter.writeElementString("clientId", bankFront.org);
        xmlWriter.writeElementString("userId", bankFront.loginName);
        xmlWriter.writeElementString("userPswd", bankFront.loginPasswd);
        xmlWriter.writeElementString("language", getCharset());
        xmlWriter.writeElementString("appId", "nsbdes");
        xmlWriter.writeElementString("appVer", "201");
        xmlWriter.writeEndElement();
    }

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    protected String[] sendToBank(String p_reqStr) throws Exception {
        return this.sendToBank(p_reqStr, false);
    }

    /**
     * 发送银行后是否进入线程等待
     *
     * @param p_reqStr
     * @param waitSleep
     * @return
     * @throws Exception
     */
    protected String[] sendToBank(String p_reqStr, boolean waitSleep) throws Exception {
        return this.sendToBank(p_reqStr, waitSleep, "", "");
    }
    protected String[] sendToBank(String p_reqStr, boolean waitSleep, String transType, String commandCode) throws Exception {
        String[] retStr = new String[]{"", ""};
        if(StringHelper.hasAnyChar(transType) && StringHelper.hasAnyChar(commandCode)) {
            this.detailSimulateForBank(bankFront.bankCode, transType, commandCode, p_reqStr, retStr);
            if (retStr[1].length() > 0) {
                return retStr;
            }
        }
        WriteBankLogLn("2.提交银行的地址：" + bankFront.serverURL);
        WriteBankLogStep2(p_reqStr);

        WebRequest tmpWebRequest = new WebRequest(bankFront.serverURL);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Content-Type", "application/x-NS-BDES");
        tmpWebRequest.setRequestProperty("Connection", "Close");
        String charsetName = getCharset();
        byte[] tmpUpBytes = p_reqStr.getBytes(charsetName);
        retStr = tmpWebRequest.upload(tmpUpBytes, charsetName);
        if (waitSleep) {
            WriteBankLogStep3(retStr[1]);
            String waitSecsEachReq = getBankConfig().getValueAsString("waitSecsEachReq");
            if (waitSecsEachReq.length() > 0) {
                Thread.sleep(Long.parseLong(waitSecsEachReq) * 1000);
            } else {
                Thread.sleep(5000);
            }
        }else{
            WriteBankLogStep3(FieldHiddenUtil.wordHiddle(retStr[1],new String[]{"DownloadFileContent"}));
        }

        return retStr;
    }

    //上送格式为json格式
    protected  String[] sendToATS(String jsonData) throws Exception{
        String[] retStr = new String[]{"",""};
        WriteBankLogLn("2.提交ATS的地址："+ FGBiz.dspCenter.dspSet.receiptPushServerUrl);


        //发送银行前置
        WebRequest tmpRequest = new WebRequest(FGBiz.dspCenter.dspSet.receiptPushServerUrl);
        tmpRequest.setConnectTimeout(60000);
        tmpRequest.setRequestProperty("connection", "Close");
        tmpRequest.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        String charsetName = getCharset();
        WriteBankLogLn("3.推送给ATS的json数据"+jsonData);
        byte[] tmpWriteBytes = jsonData.getBytes(charsetName);
        retStr = tmpRequest.upload(tmpWriteBytes, charsetName);
        WriteBankLogLn("4.返回的数据"+retStr[1]);

        return retStr;
    }
    
    private static TransIDHelper idHelper = new TransIDHelper(1, 999999);

    /**transID，12位=2时2分2秒+6位*/
    protected String getQryTransID(){
        Date tmpDateNow = new Date();
        return Format.Time6Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }
    
    /**<trnId>客户端产生的交易唯一标志（必输，但无作用） 64*/
    protected String getTrnId(){
    	Date tmpDateNow = new Date();
        return Format.DateTime14Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    /**
     * 票据背面信息查询业务转换
     * 交易类型代码 2  承兑 3  收票 4  撤票 10  背书转让 11  贴现 12  回购式贴现赎回 13  转贴现
     * 14  回购式转贴现赎回 15  再贴现 16  回购式再贴现赎回 25  央行卖出商业汇票 17  保证
     * 18  质押 19  质押解除 20  提示付款 21  逾期提示付款 22  追索 23  追索同意清偿
     * @return
     */
    protected String getTransCode(String billType){
        String transCode="";
        if(!StringHelper.isNullOrEmpty(billType)){
            if(billType.contains("_")){
                if("1_1".equals(billType)){
                    transCode="11";
                }else if("3_1".equals(billType)){
                    transCode="13";
                }else if("5_1".equals(billType)){
                    transCode="15";
                }
            }else {
                switch (Integer.parseInt(billType)){
                    case 0:transCode="10";break;//背书
                    case 1:transCode="11";break;//买断式贴现
                    //case 1_1:transCode="11";break;//回购式贴现
                    case 2:transCode="12";break;//回购式贴现赎回
                    case 3:transCode="13";break;//买断式转贴现
                    //case 3_1:transCode="13";break;//回购式转贴现
                    case 4:transCode="14";break;//回购式转贴现赎回
                    case 5:transCode="15";break;//买断式再贴现
                    //case 5_1:transCode="15";break;//回购式再贴现
                    case 6:transCode="16";break;//回购式再贴现赎回
                    case 7:transCode="25";break;//央行卖出商业汇票
                    case 8:transCode="17";break;//保证
                    case 9:transCode="18";break;//质押
                    case 10:transCode="20";break;//提示付款
                    case 11:transCode="22";break;//
                    default:transCode="";
                }
            }
        }
        return transCode;
    }

    /**
     * 票据类型转换
     * busiType：1-出票 2-承兑 3-收票 4-背书转让 5-质押 6-解质押 7-出票保证 8-承兑保证 9-背书保证 10-贴现 11-回购式贴现赎回 12-提示付款 13-追索 14-同意清偿
     * 银行：1、 提交出票2、 出票交付3、 收到承兑4、 未用退回5、 转让签收6、 背书转出7、 申请贴现8、 申请质押9、 解除质押10、 发出托收11、 收到托收12、 提示承兑13、 收票签收14、 保证申请15、 收到提示保证16、 收到质押17、 票据管家存票18、 解质押退回19、 票据管家取票20、 发出追索21、 收到追索22、 发出清偿23、 收到清偿申请
     * operType：1-申请 2-签收 3-驳回 4-撤销
     * @param busiType
     * @return
     */
    protected String getTranType(String busiType,String operType){
        String transCode="";
        if(!StringHelper.isNullOrEmpty(busiType) && !StringHelper.isNullOrEmpty(operType)){
                switch (Integer.parseInt(busiType)){
                    case 1:
                        if("1".equals(operType)){
                            transCode="1";//出票
                        }else if("4".equals(operType)){
                            transCode="4";//撤票ok
                        }break;//出票
                    case 2:
                        if("1".equals(operType) || "4".equals(operType)){
                            transCode="12";//提示承兑ok
                        }else if("2".equals(operType) || "3".equals(operType)){
                            transCode="3";//收到承兑
                        }break;//承兑
                    case 3:
                        if("1".equals(operType) || "4".equals(operType)){
                            transCode="2";//提示收票ok
                        }else if("2".equals(operType) || "3".equals(operType)){
                            transCode="13";//收票签收
                        }break;//收票
                    case 4:
                        if("1".equals(operType) || "4".equals(operType)){
                            transCode="6";//背书转让ok
                        }else if("2".equals(operType) || "3".equals(operType)){
                            transCode="5";//转让签收ok
                        }break;//背书转让
                    case 5:
                        if("1".equals(operType) || "4".equals(operType)){
                            transCode="8";//申请质押
                        }else if("2".equals(operType) || "3".equals(operType)){
                            transCode="16";//收到质押
                        }break;//质押
                    case 6:
                        if("1".equals(operType) || "4".equals(operType)){
                            transCode="9";//解除质押
                        }else if("2".equals(operType) || "3".equals(operType)){
                            transCode="18";//解质押退回
                        }break;//解质押
                    case 7:transCode="14";break;//出票保证
                    case 8:transCode="14";break;//承兑保证
                    case 9:transCode="14";break;//背书保证
                    case 10:
                        if("1".equals(operType) || "4".equals(operType)){
                            transCode="7";//申请贴现
                        }else if("2".equals(operType) || "3".equals(operType)){
                            transCode="7";//贴现签收
                        }break;//贴现
                    //case 11:transCode="22";break;//回购式贴现赎回
                    case 12:
                        if("1".equals(operType) || "4".equals(operType)){
                            transCode="10";//发起托收ok
                        }else if("2".equals(operType) || "3".equals(operType)){
                            transCode="11";//收到托收ok
                        }break;//提示付款
                    case 13:
                        if("1".equals(operType) || "4".equals(operType)){
                            transCode="20";//发出追索
                        }else if("2".equals(operType) || "3".equals(operType)){
                            transCode="21";//收到追索
                        }break;//追索
                    case 14:
                        if("1".equals(operType) || "4".equals(operType)){
                            transCode="22";//发出清偿
                        }else if("2".equals(operType) || "3".equals(operType)){
                            transCode="23";//收到清偿
                        }break;//同意清偿
                    default:transCode="";
                }
        }
        return transCode;
    }


    /**
     * 根据票据编号查询票据状态
     * @param billId 票据id
     * @param actNum 账号
     * @return
     * @throws Exception
     */
    protected String getBillStatus(String billId,String actNum) throws Exception{
        WriteBankLogLn("========开始根据票据Id【"+billId+"】和账号【"+actNum+"】查询票据状态========");
        String billState="";//票据状态
        //赋值通用参数
        CMBC01Header bankHeader = new CMBC01Header();
        bankHeader.trnCode = "QryDraftInfo";
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        //写入通用的头部节点
        writeCommonHeader(xmlWriter, bankHeader);
        xmlWriter.writeStartElement("xDataBody");
        xmlWriter.writeElementString("trnId", getQryTransID());//客户端产生的交易唯一标志
        xmlWriter.writeElementString("rgctId", billId);//票据id
        xmlWriter.writeElementString("appAcNo", actNum);//客户账号
        xmlWriter.writeEndElement();
        xmlWriter.writeEndDocument();
        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
            if (tmpBkReader != null) {
                String tmpRetCode = tmpBkReader.getFirstText("/CMBC/responseHeader/status/code");
                if ("0".equals(tmpRetCode)) {
                    billState = tmpBkReader.getFirstText("/CMBC/xDataBody/curStatusName");//票据状态
                }
            }
        }
        WriteBankLogLn("========票据Id【"+billId+"】和账号【"+actNum+"】查询到票据状态为【"+billState+"】，查询完成========");
        return billState;
    }
}
